//
//  YZMAnnouncementListViewController.m
//  YZMicroStock
//
//  Created by Lv.Dongdong on 16/4/25.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMAnnouncementListViewController.h"
#import "MJRefreshNormalHeader.h"
#import "MJRefreshAutoNormalFooter.h"
#import "YZMResultView.h"
#import "YZClient+Account.h"
#import "YZGeneralResultModel.h"
#import "YZMAnnouncementModel.h"
#import "YZMPageService.h"
#import "YZMAnnouncementListModel.h"
#import "YZMAnnouncementListCell.h"

static NSString *const sYZMAnnouncementCellID = @"YZMAnnouncementListCellID";

@interface YZMAnnouncementListViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) MJRefreshNormalHeader *refreshHeader;
@property (nonatomic, strong) MJRefreshAutoNormalFooter *refreshFooter;
@property (nonatomic, strong) YZMResultView *resultView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) YZMPageService *pageService;

@end

@implementation YZMAnnouncementListViewController

- (id)init {
    if (self = [super init]) {
        self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
        self.title = @"公告列表";
        self.hidesBottomBarWhenPushed = YES;
        self.dataArray = [NSMutableArray array];
    }
    return self;
}

- (YZMPageService *)pageService {
    
    if (!_pageService) {
        
        _pageService = [[YZMPageService alloc] init];
    }
    
    return _pageService;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createTableView];
    [self fetchAnnouncementListFirstPage];
}

#pragma mark -- Network Request

- (void)fetchAnnouncementList {
    
    [_refreshFooter resetNoMoreData];
    _refreshFooter.stateLabel.text = @"";
    
    /*无网处理*/
    if (kNetworkNotReachability) {
        
        [self endRefresh];
        
        if (self.dataArray.count == 0) {
            
            _resultView.status = YZM_RESULT_STATUS_FOR_NO_WIFI;
            _tableView.mj_header = nil;
            _tableView.mj_footer = nil;
            
        }else{
            _resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
            [self.tableView reloadData];
            [NSError yz_showMessageForNoWifi];
        }
        
        return;
    }
    
    if (!self.dataArray || self.dataArray.count == 0) {
        
        _resultView.status = YZM_RESULT_STATUS_FOR_LOADING;
    }
    
    [YZClient fetchNoticeListSuccess:^(NSURLSessionDataTask *task, id responseObject) {
        
        [self endRefresh];
        _tableView.mj_header = _refreshHeader;
        _tableView.mj_footer = _refreshFooter;
        _resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
        
        YZGeneralResultModel *topModel = responseObject;
        
        if (topModel.success) {
            
            YZMAnnouncementModel *AnnouncementDetail = topModel.data;
            
            NSArray *AnnouncementList = AnnouncementDetail.items;
            NSInteger pageIndex = AnnouncementDetail.pageIndex;
            if (pageIndex == self.pageService.minPage) {
                
                /*保存历史数据*/
                [self.dataArray removeAllObjects];
                [self.dataArray addObjectsFromArray:AnnouncementList];
                
                if (!AnnouncementList || AnnouncementList.count == 0) {
                    
                    _resultView.status = YZM_RESULT_STATUS_FOR_NO_DATA;
                }
                
                self.pageService.maxPage = AnnouncementDetail.totalPage;
                
            } else {
                
                if (AnnouncementList.count != 0) {
                    
                    [self.dataArray addObjectsFromArray:AnnouncementList];
                }
            }
            
            if (self.dataArray.count != 0 && (AnnouncementList.count < self.pageService.pageSize || [_pageService isMaxPage])) {
                
                [_refreshFooter endRefreshingWithNoMoreData];
                _refreshFooter.stateLabel.text = @"暂无更多公告";
            } else {
                
                [_refreshFooter resetNoMoreData];
            }
            
            [self.tableView reloadData];
            [self.pageService effectChange];
        } else {
            
            if (!self.dataArray || self.dataArray.count == 0) {
                
                [_resultView syncStatusWithError:[NSError yz_errorWithMessage:topModel.resultMessage]];
                _tableView.mj_header = nil;
                _tableView.mj_footer = nil;
                
            } else {
                
                [topModel showMessage];
            }
        }
        
    } failure:^(NSError *error) {
        
        if (self.dataArray.count == 0) {
            
            [_resultView syncStatusWithError:error];
            _tableView.mj_header = nil;
            _tableView.mj_footer = nil;
            
        } else {
            
            [error yz_showMessage];
        }
        
    }];
    
}

- (void)fetchAnnouncementListFirstPage{
    
    [self fetchAnnouncementListFirstPageWithRemoveDataFlag:NO];
}

- (void)fetchAnnouncementListFirstPageWithRemoveDataFlag:(BOOL)removeFlag{
    
    if (removeFlag) {
        
        [self.dataArray removeAllObjects];
        [self.tableView reloadData];
    }
    
    [self.pageService preChangeWithPage:self.pageService.minPage andTimeEnd:YES];
    [self fetchAnnouncementList];
}

- (void)fechAnnouncementListNextPage{
    
    if (self.dataArray.count == 0) {
        
        [self.pageService preChangeWithPage:self.pageService.minPage andTimeEnd:YES];
    } else {
        
        [self.pageService preChangeWithPage:self.pageService.nextPage  andTimeEnd:YES];
    }
    [self fetchAnnouncementList];
}

- (void)createTableView {
    
    WS(ws)
    self.tableView = [[UITableView alloc] init];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.backgroundColor = [YZMAppStyle appBackgroundColor];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(ws.view);
    }];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    [self.tableView registerClass:[YZMAnnouncementListCell class] forCellReuseIdentifier:sYZMAnnouncementCellID];
    
    _refreshHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(fetchAnnouncementListFirstPage)];
    _tableView.mj_header = _refreshHeader;
    
    _refreshFooter = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(fechAnnouncementListNextPage)];
    _tableView.mj_footer = _refreshFooter;
    
    _resultView = [YZMResultView new];
    [self.view addSubview:_resultView];
    [_resultView mas_makeConstraints:^(MASConstraintMaker *maker){
        maker.edges.equalTo(ws.view);
    }];
    _resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
    _resultView.retryAction = ^(void){
        [ws fechAnnouncementListNextPage];
    };
    
}

- (void)endRefresh{
    
    if (_refreshHeader.isRefreshing) {
        
        [_refreshHeader endRefreshing];
    }
    
    if (_refreshFooter.isRefreshing) {
        
        [_refreshFooter endRefreshing];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- TableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YZMAnnouncementListCell *cell = [tableView dequeueReusableCellWithIdentifier:sYZMAnnouncementCellID forIndexPath:indexPath];
    
    YZMIndexCount indexCount;
    indexCount.index = indexPath.row;
    indexCount.count = self.dataArray.count;
    cell.indexCount = indexCount;
    
    if (indexPath.row == 0) {
        
        UIView *lineView = [YZMAppStyle splitLine];
        [cell.contentView addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.left.right.equalTo(cell.contentView);
        }];
    }
    
    YZMAnnouncementListModel *tempDic = self.dataArray[indexPath.row];
    
    [cell showCellView:tempDic];
    
    return cell;
}

#pragma mark -- TableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    YZMAnnouncementListModel *tempDic = self.dataArray[indexPath.row];
    
    [YZMHCMInstance pushViewControllerWithName:@"annDetail" andParams:@{@"noticeId":@(tempDic.noticeId)}];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    

    return 70;
}

@end
